package com.example.demo.services;


import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.stereotype.Component;

import java.util.List;

// 监听springboot启动，并给MongoDB Collections创建索引（为了实现获取最后一次聊天信息的功能）
@Component
public class MongoIndexApplicationListener implements ApplicationListener<ContextRefreshedEvent> {


    private final MongoTemplate mongoTemplate;

    public MongoIndexApplicationListener(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public void onApplicationEvent(@NotNull ContextRefreshedEvent event) {
//        确保创建索引
        ensureIndexes();
    }

//    这是给一个Collection创建索引的逻辑
//    private void ensureIndexes() {
//        IndexOperations indexOps = mongoTemplate.indexOps("chatMessages");
//        List<IndexInfo> existingIndexes = indexOps.getIndexInfo();
//        String collectionPrivateIndexName = "private-message-timeStamp-1";   // 索引名称

    /// /        在创建索引之前先检查索引是否存在，避免重复创建
//        boolean indexExists = existingIndexes.stream().anyMatch(idx -> idx.getName().equals(collectionPrivateIndexName));
//        if (!indexExists) {
//            indexOps.ensureIndex(new Index().on("timeStamp", Sort.Direction.DESC).named(collectionPrivateIndexName));    // 这里创建降序索引
//        }
//    }

//    这是给多个Collections创建索引的逻辑
    private void ensureIndexes() {
//        Create index for first Collections
        String collectionPrivateName = "chatMessages";
        String collectionPrivateIndexName = "private-message-timeStamp-index-chat-1";
        ensureIndexForCollection(collectionPrivateName, collectionPrivateIndexName);

//        Create index for second Collections
        String collectionPublicName = "group_msg";
        String collectionPublicIndexName = "public-message-timeStamp-index-chat-1";
        ensureIndexForCollection(collectionPublicName, collectionPublicIndexName);
    }

    //    检查索引是否存在
    private void ensureIndexForCollection(String collectionName, String indexName) {
        IndexOperations indexOperations = mongoTemplate.indexOps(collectionName);
        List<IndexInfo> existingIndexes = indexOperations.getIndexInfo();

//        在创建索引之前先检查索引是否存在，避免重复创建
        boolean indexExists = existingIndexes.stream().anyMatch(index -> index.getName().equals(indexName));
        if (!indexExists) {
            indexOperations.ensureIndex(new Index().on("timeStamp", Sort.Direction.DESC).named(indexName));       // 创建降序索引
        }
        return; 
    }


}
